﻿using System.Runtime.Serialization;
using BaseTypesLib.Interfaces;
using System.Xml.Linq;
using System.Linq;

namespace BaseTypesLib.Model
{
    [DataContract(IsReference=true)]
    public abstract class TextField:Field, IEditable, IReadOnly
    {
        //TODO add TextField style bits
        private bool editable, readOnly;
        private string label, text;

        [DataMember]
        public string Text
        {
            get { return text; }
            set
            {
                if (text != value)
                {
                    text = value;
                    OnPropertyChanged("Text");
                }
            }
        }
        [DataMember]
        public string Label
        {
            get { return label; }
            set
            {
                if (label != value)
                {
                    label = value;
                    OnPropertyChanged("Label");
                }
            }
        }

        [DataMember]
        public bool ReadOnly
        {
            get { return readOnly; }
            set
            {
                if (readOnly != value)
                {
                    readOnly = value;
                    OnPropertyChanged("ReadOnly");
                }
            }
        }

        [DataMember]
        public bool Editable
        {
            get { return editable; }
            set
            {
                if (editable != value)
                {
                    editable = value;
                    OnPropertyChanged("Editable");
                }
            }
        }

        protected override XElement GetXmlElement()
        {
            XElement el = base.GetXmlElement();
            if (Label != null && Label.Trim().Length > 0)
                el.SetAttributeValue("Label", Label.Trim());
            if (Text != null && Text.Trim().Length > 0)
                el.SetAttributeValue("Text", Text.Trim());

            if (ReadOnly)
                el.SetAttributeValue("ReadOnly", ReadOnly);
            if (!Editable)
                el.SetAttributeValue("Editable", Editable);

            return el;
        }
        protected override void FromXmlElement(XElement elem)
        {
            base.FromXmlElement(elem);
            var lbl = elem.Attributes("Label").FirstOrDefault();
            if (lbl != null)
                Label = lbl.Value;
            var txt = elem.Attributes("Text").FirstOrDefault();
            if (txt != null)
                Text = txt.Value;

            var ro = elem.Attributes("ReadOnly").FirstOrDefault();
            if (ro != null) ReadOnly = (bool)ro;
            var e = elem.Attributes("Editable").FirstOrDefault();
            if (e != null) Editable = (bool)e;
        }
    }
}
